import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';
import '../../../core/providers/discussion_hub_provider.dart';
import '../../../core/providers/global_state_coordinator.dart';
import '../../../core/utils/app_utils.dart';

class CommunityQuestionCreationPage extends StatefulWidget {
  const CommunityQuestionCreationPage({super.key});

  @override
  State<CommunityQuestionCreationPage> createState() =>
      _CommunityQuestionCreationPageState();
}

class _CommunityQuestionCreationPageState
    extends State<CommunityQuestionCreationPage> {
  final TextEditingController _titleController = TextEditingController();
  final FocusNode _titleFocusNode = FocusNode();
  bool _isSubmitting = false;

  @override
  void dispose() {
    _titleController.dispose();
    _titleFocusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/images/my-bg.png'),
          fit: BoxFit.cover,
        ),
      ),
      child: Scaffold(
        backgroundColor: Colors.transparent,
        body: SafeArea(
          child: Column(
            children: [
              _buildNavigationHeader(),
              Expanded(
                child: Padding(
                  padding: EdgeInsets.symmetric(horizontal: 24.w),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [SizedBox(height: 40.h), _buildQuestionInput()],
                  ),
                ),
              ),
              _buildSubmissionButton(),
              SizedBox(height: 40.h),
              _buildFooterText(),
              SizedBox(height: 60.h),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildNavigationHeader() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: Row(
        children: [
          GestureDetector(
            onTap: () => Navigator.of(context).pop(),
            child: Icon(Icons.arrow_back_ios, color: Colors.white, size: 24.w),
          ),
          Expanded(
            child: Center(
              child: Text(
                'Post',
                style: TextStyle(
                  fontSize: 20.sp,
                  fontWeight: FontWeight.w600,
                  color: Colors.white,
                  fontFamily: 'Poppins',
                ),
              ),
            ),
          ),
          SizedBox(width: 24.w),
        ],
      ),
    );
  }

  Widget _buildQuestionInput() {
    return Expanded(
      child: Container(
        width: double.infinity,
        margin: EdgeInsets.only(bottom: 20.h),
        decoration: BoxDecoration(
          color: Colors.transparent,
          borderRadius: BorderRadius.circular(16.r),
        ),
        child: TextField(
          controller: _titleController,
          focusNode: _titleFocusNode,
          style: TextStyle(
            fontSize: 16.sp,
            color: Colors.white,
            fontFamily: 'Poppins',
            fontWeight: FontWeight.w400,
            height: 1.5,
          ),
          decoration: InputDecoration(
            hintText: 'Write Down Your Question And Let Everyone Help You~',
            hintStyle: TextStyle(
              fontSize: 16.sp,
              color: Colors.white.withValues(alpha: 0.6),
              fontFamily: 'Poppins',
              fontWeight: FontWeight.w400,
              height: 1.5,
            ),
            border: InputBorder.none,
            contentPadding: EdgeInsets.all(0),
          ),
          maxLines: null,
          expands: true,
          textAlignVertical: TextAlignVertical.top,
          textInputAction: TextInputAction.done,
        ),
      ),
    );
  }

  Widget _buildSubmissionButton() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 24.w),
      width: double.infinity,
      child: ElevatedButton(
        onPressed: _isSubmitting ? null : _handleSubmitQuestion,
        style: ElevatedButton.styleFrom(
          backgroundColor: const Color(0xFFCD8B76),
          foregroundColor: Colors.white,
          padding: EdgeInsets.symmetric(vertical: 16.h),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(25.r),
          ),
          elevation: 0,
        ),
        child:
            _isSubmitting
                ? SizedBox(
                  height: 20.h,
                  width: 20.w,
                  child: const CircularProgressIndicator(
                    strokeWidth: 2,
                    valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                  ),
                )
                : Text(
                  'Release',
                  style: TextStyle(
                    fontSize: 16.sp,
                    fontWeight: FontWeight.w600,
                    fontFamily: 'Poppins',
                  ),
                ),
      ),
    );
  }

  Widget _buildFooterText() {
    return GestureDetector(
      onTap: () {
        AppUtils.openUrl(
          'https://www.freeprivacypolicy.com/live/82e54f5c-a3a3-4bc8-a08a-0da176425cf4',
        );
      },
      child: Text(
        'EULA',
        style: TextStyle(
          fontSize: 12.sp,
          decoration: TextDecoration.underline,
          fontWeight: FontWeight.w500,
          color: Colors.white.withValues(alpha: 0.7),
          decorationColor: Colors.white.withValues(alpha: 0.7),
          fontFamily: 'Poppins',
        ),
      ),
    );
  }

  void _handleSubmitQuestion() async {
    // 验证输入
    if (_titleController.text.trim().isEmpty) {
      AppUtils.showWarning(
        context,
        'Please write down your question',
        title: 'Missing Question',
      );
      _titleFocusNode.requestFocus();
      return;
    }

    // 检查用户登录状态
    final coordinator = context.read<GlobalStateCoordinator>();
    if (!coordinator.isLoggedIn) {
      AppUtils.showLoginRequired(
        context,
        message: 'Please login to post a question',
        title: 'Login Required',
        onLogin: () {
          Navigator.of(context).pushNamed('/login');
        },
      );
      return;
    }

    // 开始提交
    setState(() {
      _isSubmitting = true;
    });

    AppUtils.showLoading(context, message: 'Posting question...');

    try {
      final discussionProvider = context.read<DiscussionHubProvider>();
      final currentUser = coordinator.currentUser!;

      final questionText = _titleController.text.trim();

      await discussionProvider.createNewTopic(
        title: questionText,
        description: questionText,
        creatorId: currentUser.id,
        creatorName: currentUser.userName,
        creatorAvatar: currentUser.avatar,
        tags: ['music', 'help'],
      );

      if (mounted) {
        AppUtils.hideLoading(context);

        AppUtils.showSuccess(
          context,
          'Your question has been posted successfully!',
          title: 'Question Posted',
        );

        Future.delayed(const Duration(milliseconds: 1500), () {
          if (mounted) {
            Navigator.of(context).pop();
          }
        });
      }
    } catch (e) {
      if (mounted) {
        AppUtils.showError(
          context,
          'Failed to post question. Please try again.',
          title: 'Post Failed',
        );
      }
    } finally {
      if (mounted) {
        setState(() {
          _isSubmitting = false;
        });
      }
    }
  }
}
